#include "tbag.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include <iostream>
using namespace std;

// ïàðàëëåëüíîå óìíîæåíèå ìàòðèö
// ñ èñïîëüçîâàíèåì ïîðòôåëÿ çàäà÷

const int P=10;//÷èñëî ðàáî÷èõ ïðîöåññîâ (íå èñïîëüçóåòñÿ â MPI)

const int N=10000;
float c[N][N];

void swap(float* i, float* j)
{
   float temp;
   temp=*i;
   *i=*j;
   *j=temp;
}

void quickSort(float* a, const long n) {
  long i = 0, j = n;
  float  pivot = a[n / 2]; // îïîðíûé ýëåìåíò
 
  do {
    while (a[i] < pivot) i++;
    while (a[j] > pivot) j--;
 
    if (i <= j) {
     swap(&a[i], &a[j]);
      i++; j--;
    }
  } while (i <= j);
 
    if (j > 0) quickSort(a, j);
    if (n > i) quickSort(a + i, n - i);
}


class TaskBag:public TEMPLET::TBag{
public:
	class TaskBagTask:public TBag::Task{
	public:
		TaskBagTask():TBag::Task(){}
		virtual~TaskBagTask(){}

		void send_task()  {}// çàïèñü çàäà÷è â ïîòîê  (òîëüêî äëÿ ðàñïðåäåëåííîé ðåàëèçàöèè)
		void recv_task()  {}// ÷åòíèå çàäà÷è èç ïîòîêà (òîëüêî äëÿ ðàñïðåäåëåííîé ðåàëèçàöèè)
		void send_result(){}// çàïèñü ðåçóëüòàòà â ïîòîê (òîëüêî äëÿ ðàñïðåäåëåííîé ðåàëèçàöèè)
		void recv_result(){}// ÷òåíèå ðåçóëüòàòà èç ïîòîêà (òîëüêî äëÿ ðàñïðåäåëåííîé ðåàëèçàöèè)

		int num;// íîìåð âû÷èñëÿåìîé ñòðîêè
	};
public:
	TaskBag(int num_prc,int argc, char* argv[]):TBag(num_prc,argc,argv){
		cur=0; 
	}
	virtual ~TaskBag(){}
	TBag::Task* createTask(){return new TaskBagTask;}

	bool if_job(){return cur<N;}
	void put(Task*t){TaskBagTask* mt=(TaskBagTask*)t; }
	void get(Task*t){TaskBagTask* mt=(TaskBagTask*)t; mt->num=cur;cur+=1;}
	void proc(Task*t){TaskBagTask* mt=(TaskBagTask*)t;
		quickSort(c[mt->num],N-1);
	}
int cur;
	
};

int main(int argc, char* argv[])
{
	TaskBag bag(P,argc,argv);//èñïîëüçóåì P ðàáî÷èõ ïðîöåññîâ(íå èñïîëüçóåòñÿ â MPI)

	// èíèöèàëèçàöèÿ
	srand( (unsigned)time( NULL ) );
	for (int l=0;l<N;l++)
	for(int m=0;m<N;m++)c[l][m]=(float)(rand()%9);


	// ïàðàëëåëüíîå óìíîæåíèå ìàòðèö
	bag.run();
	cout<<"\nspeedup = "<<bag.speedup();//1-ïðè ëîãè÷åñêîé îòëàäêå,
	//P-ïðè ïàðàëëåëüíîì âûïîëåíèè,
	//ïðåäñêàçûâàåìîå çíà÷åíèå óñêîðåíèÿ äëÿ äàííîãî P ïðè äèñêðåòíî-ñîáûòèéíîé ýìóëÿöèè âû÷èñëåíèé
	//âíèìàíèå! ðåæèì ýìóëÿöèè äîñòóïåí òîëüêî äëÿ ÎÑ Windows 
	
	cout<<"\nduration = "<<bag.duration()<< " sec\n";

		for(int r=0;r<N;r++){
		for(int g=0;g<N;g++)
			// cout << c[r][g]<<"  ";
		cout<<"\n";
    }
		return 0;
}